package com.eastfair.handler;

import com.eastfair.cache.gateway.TokenCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.core.model.CacheKey;
import com.eastfair.core.model.CacheKeyBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * token处理
 * ligang
 * 2021-09-17
 */
@Component
public class EfTokenHandler {

    @Autowired
    protected CacheOps cacheOps;

    /**
     * redis 记录token的key值
     */
    private CacheKeyBuilder tokenCacheKey = new TokenCacheKeyBuilder();

    /**
     * 添加token
     *
     * @param token        token值
     * @param terminalType 场景来源
     * @param userId       用户id
     */
    public void addToken(String token, String terminalType, Long userId) {
        CacheKey key = tokenCacheKey.key(getKeyId(terminalType,userId));
        cacheOps.set(key, token);
    }

    /**
     * 查询token
     *
     * @param terminalType 场景来源
     * @param userId       用户id
     * @return
     */
    public String findToken(String terminalType, Long userId) {
        //主键id
        CacheKey key = tokenCacheKey.key(getKeyId(terminalType,userId));
        String token = cacheOps.get(key);
        return token;
    }

    /**
     * 删除token
     *
     * @param terminalType 场景来源
     * @param userId       用户id
     */
    public void delToken(String terminalType, Long userId) {
        CacheKey key = tokenCacheKey.key(getKeyId(terminalType,userId));
        cacheOps.del(key);
    }

    private String getKeyId(String terminalType, Long userId){
        return userId + "," + terminalType;
    }
}
